<?php
/**
 * Created by yd
 * User: xiaojun.lan
 * Date: 2018/5/15
 * Time: 17:10
 */

namespace app\worker\controller;

use Workerman\Worker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use GatewayWorker\BusinessWorker;

class Server
{

    protected $register = true;// 是否将当前服务器配置为 register 服务器
    protected $registerIpPort = '192.168.218.133:1236';// register 服务器的ip和端口（一定要填写，不管 register 是true还是false）

    protected $businessWorker = true; // 是否将当前服务器配置为 business_worker 服务器
    protected $businessWorkerCount = 4;  //  当前business_worker服务器开启的进程数

    protected $gateway = true; // 是否将当前服务器配置为 gateway 服务器
    protected $gatewayLanIp = '192.168.218.133';// 当前 gateway 服务器ip地址（内网ip）
    protected $gatewayWebSocket = '192.168.218.133:8082';// 服务器webSocket地址和端口，提供客户端连接，一般是当前gateway服务器外网ip和端口
    protected $gatewayCount = 4; // 当前gateway服务器的进程数
    protected $gatewayStartPort = 2300;/*当前gateway服务器的内部通讯起始端口,如果gateway_count为4，
                                        则一般会使用2300 2301 2302 2303 4个端口作为内部通讯端口*/

    /**
     * 构造函数
     * @access public
     */
    public function __construct(){

        if($this->register){
            //初始化各个GatewayWorker
            //初始化register register 服务必须是text协议
//            $register = new Register('text://0.0.0.0:1236');
            $register = new Register('text://'.$this->registerIpPort);
        }

        if($this->businessWorker){
            //初始化 bussinessWorker 进程
            $worker = new BusinessWorker();
            // worker名称
            $worker->name = 'WorkerBusinessWorker';
            // bussinessWorker进程数量
            $worker->count = $this->businessWorkerCount;
            // 服务注册地址
//            $worker->registerAddress = '127.0.0.1:1236';
            $worker->registerAddress = $this->registerIpPort;
            //设置处理业务的类,此处制定Events的命名空间
            $worker->eventHandler = 'app\worker\controller\Events';
        }

        if($this->gateway){
            // 初始化 gateway 进程 ， 客户端连接Gateway
            $gateway = new Gateway("websocket://".$this->gatewayWebSocket);
            // 设置名称，方便status时查看
            $gateway->name = 'WorkerGateway';
            $gateway->count = $this->gatewayCount;
            // 分布式部署时请设置成内网ip（非127.0.0.1）
//            $gateway->lanIp = '172.17.249.223';
            $gateway->lanIp = $this->gatewayLanIp;
            // 内部通讯起始端口，假如$gateway->count=4，起始端口为4000
            // 则一般会使用4000 4001 4002 4003 4个端口作为内部通讯端口
            $gateway->startPort = $this->gatewayStartPort;
            // 心跳间隔
            $gateway->pingInterval = 10;
            // 心跳数据
            $gateway->pingData = '{"type":"ping"}';
            // 服务注册地址
//            $gateway->registerAddress = '127.0.0.1:1236';
            $gateway->registerAddress = $this->registerIpPort;
        }

        //运行所有Worker;
        Worker::runAll();

    }

}
